package com.wu.store.service.impl;

import com.wu.store.dao.CategoryDao;
import com.wu.store.entity.Category;
import com.wu.store.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CategoryServiceImpl implements CategoryService {

	@Autowired
	private CategoryDao categoryDao;

	@Override
	public List<Category> getCategories(String keyword) {
		List<Category> categories = categoryDao.selectByKeywordAndStatus(keyword, 1);
		return categories;
	}

	@Override
	public boolean isNameValid(Category targetCategory) throws Exception {
		Category category = categoryDao.selectByName(targetCategory.getName());
		if (category == null) {
			return true;
		}
		if (!category.getId().equals(targetCategory.getId())) {
			throw new Exception("该类别名称已被占用");
		}
		return true;
	}

	@Override
	public Long save(Category category) {
		if (category.getId() == null) {
			category.setCreateTime(new Date());
			categoryDao.add(category);
		} else {
			category.setUpdateTime(new Date());
			categoryDao.update(category);
		}
		return category.getId();
	}


	@Override
	public boolean deleteCategoryById(Integer id) throws Exception {
		Category category = categoryDao.selectById(id);
		if (category == null) {
			throw new Exception("该类别不存在");
		}
		category.setStatus(0);
		categoryDao.update(category);
		return true;
	}
}
